﻿/*
 * Cratos Server - WCF Service
 * Cratos WCF Collection Engine class
 * 
 * Copyright (c) 2011-2012 Draco
 * 
 * This file is part of Cratos.
 * 
 * Cratos is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * Cratos is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Cratos.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *       .==.        .==.
 *      //'^\\      //^'\\
 *     // ^ ^\(\__/)/^ ^^\\
 *    //^ ^^ ^/6  6\ ^^ ^ \\
 *   //^ ^^ ^/( .. )\^ ^ ^ \\
 *  // ^^ ^/\| V""V|/\^ ^ ^ \\
 * //^^/\/ /  '~~'  \ \/\^ ^ \\
 *  ------------------------------------
 *  HERE BE DRAGONS
 *  
 *  Johan Dercksen - johan@draco.co.za
 */
using System;
using System.Text;
using System.Linq;
using System.Threading;
using System.Collections.Generic;
using System.Collections.ObjectModel;

using Cratos.Server.Entity;
using Cratos.Tools.General;
using Cratos.Tools.DataObject;

namespace Cratos.Server.WcfService
{
	/// <summary>
	/// Cratos WCF Collection Engine class
	/// </summary>
	public class CratosWcfPagingEngine : CratosWcfEngineBase
	{
		#region Class Constant declarations
		#endregion

		#region Class Event declarations
		#endregion

		#region Class Variable declarations
		private CratosWcfContract wcfContract;
		#endregion

		#region Class Constructors & Destructors
		/// <summary>
		/// Class Constructor
		/// </summary>
		/// <param name="engineName">Engine Name</param>
		/// <param name="callbackContext">Callback Context</param>
		/// <param name="ctCratos">Cratos WCF Contract</param>
		public CratosWcfPagingEngine(string engineName, ICratosDualWcfServiceCallback callbackContext, CratosWcfContract ctCratos) :
					base(engineName, callbackContext)
		{
			// Save the incoming values
			this.wcfContract = ctCratos;
		}
		#endregion

		#region Class Properties
		#endregion

		#region Class Methods
		/// <summary>
		/// Engine Processing method
		/// </summary>
		public override void EngineProcessing()
		{
			// Declare the required variables
			object									doCratosCollection = null;
			Collection<CratosError> returnErrors;

			// Create and Setup the required object(s)
			returnErrors = new Collection<CratosError>();

			try
			{
				// Log the relevant message
				this.OnLogMessage(CratosLogSeverity.Informational, "Cratos Dual WCF Service", "CratosWcfPagingEngine()");

				// Update the EAL Data Object
				doCratosCollection = DOCratosGlobal.BinDeserialize(this.wcfContract.DOStream);

				// Update the relevant properties and Event(s)
				DOCratosHelper.SetPropertyValue(doCratosCollection, "IsClientSide", false);
				DOCratosHelper.SubscribeToEvent(doCratosCollection, "NewPage", new CollectionNewPageEventHandler(this.OnEntityNewPage));
				DOCratosHelper.SubscribeToEvent(doCratosCollection, "Error", new CollectionErrorEventHandler(this.OnEntityError));
				DOCratosHelper.SubscribeToEvent(doCratosCollection, "Completed", new CollectionCompletedEventHandler(this.OnEntityCompleted));

				// Log the relevant message
				this.OnLogMessage(CratosLogSeverity.Informational, "Cratos Dual WCF Service",
													string.Format("Processing {0} Action: {1}", doCratosCollection.GetType().Name,
																																			DOCratosHelper.GetPropertyValue(doCratosCollection, "CollectionAction")));
				// Perform the correct action
				if (!(bool)DOCratosHelper.InvokeMethod(doCratosCollection, "PerformAction", null))
				{
					// Process all errors
					foreach (CratosError currentError in ((IEnumerable<CratosError>)DOCratosHelper.GetPropertyValue(doCratosCollection, "Errors")))
					{
						returnErrors.Add(currentError);
					}
				}
			}
			catch (Exception runtimeException)
			{
				// Add the error to the Error collection
				returnErrors.Add(new CratosError("CratosWcfPagingEngine.EngineProcessing", CratosLogSeverity.Exception,
																				 "Runtime exception occurred", runtimeException));
			}
			finally
			{
				// Raise the error message if required
				if (returnErrors.Count > 0) { this.OnEntityError(returnErrors); }
			}

			// Log the relevant message
			this.OnLogMessage(CratosLogSeverity.Informational, "Cratos Dual WCF Service",
												string.Format("CratosWcfPagingEngine() Completed [Return Value: {0} ]", (returnErrors.Count <= 0)));

			// Return to calling method
			return;
		}

		/// <summary>
		/// Collection New Page event handler
		/// </summary>
		/// <param name="pageNo"></param>
		/// <param name="doCollection"></param>
		public void OnEntityNewPage(long pageNo, Collection<IDOCratos> doCollection)
		{
			// Declare the required variables
			CratosCollectionNewPageContract ctCratos;

			// Create and Setup the new Contract
			ctCratos              = new CratosCollectionNewPageContract();
			ctCratos.IsCompressed = true;
			ctCratos.PageNo       = pageNo;
			ctCratos.DOStream     = DOCratosGlobal.BinSerialize(doCollection);

			// Send the Page back to the client
			this.CallbackContext.CratosNewPage(ctCratos);

			// Log the relevant message
			this.OnLogMessage(CratosLogSeverity.Informational, "Cratos Dual WCF Service",
												string.Format("CratosWcfPagingEngine() New Page [Page No: {0} ]", pageNo));

			// Return to calling method
			return;
		}

		/// <summary>
		/// Collection New Page event handler
		/// </summary>
		/// <param name="errorCollection">Error Collection</param>
		public void OnEntityError(Collection<CratosError> errorCollection)
		{
			// Declare the required variables
			CratosCollectionErrorContract ctCratos;

			// Create and Setup the new Contract
			ctCratos        = new CratosCollectionErrorContract();
			ctCratos.Errors = errorCollection;

			// Send the Page back to the client
			this.CallbackContext.CratosError(ctCratos);

			// Log the relevant message
			this.OnLogMessage(CratosLogSeverity.Informational, "Cratos Dual WCF Service",
												string.Format("CratosWcfPagingEngine() Error Occurred [Error Count: {0}]", errorCollection.Count));

			// Return to calling method
			return;
		}

		/// <summary>
		/// Collection New Page event handler
		/// </summary>
		/// <param name="actionResult">Cratos Action result</param>
		/// <param name="doCollection">Data Object Collection</param>
		public void OnEntityCompleted(DOCratosActionResult actionResult, Collection<IDOCratos> doCollection)
		{
			// Declare the required variables
			CratosCollectionCompletedContract ctCratos;

			// Create and Setup the new Contract
			ctCratos              = new CratosCollectionCompletedContract();
			ctCratos.ActionResult = actionResult;
			ctCratos.DOStream     = DOCratosGlobal.BinSerialize(doCollection);

			// Send the Page back to the client
			this.CallbackContext.CratosCompleted(ctCratos);

			// Log the relevant message
			this.OnLogMessage(CratosLogSeverity.Informational, "Cratos Dual WCF Service",
												string.Format("CratosWcfPagingEngine() Completed [Result: {0}]", actionResult));

			// Return to calling method
			return;
		}
		#endregion

		#region Class Support Methods
		#endregion
	}
}
